package com.jzo2o.foundations.service.impl;

import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServerMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.dto.response.ServeCategoryResDTO;
import com.jzo2o.foundations.model.dto.response.ServeSimpleResDTO;
import com.jzo2o.foundations.service.IHomeService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IHomeServiceImpl implements IHomeService {
    @Resource
    RegionMapper regionMapper;
    @Resource
    ServerMapper serverMapper;



    @Override
    @Caching(
            cacheable = {
                    //result为null时,属于缓存穿透情况，缓存时间30分钟
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key = "#regionId", unless = "#result.size() != 0",
                            cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),
                    //result不为null时,永久缓存
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON, key = "#regionId", unless = "#result.size() == 0",
                            cacheManager = RedisConstants.CacheManager.FOREVER)
            }
    )
    public List<ServeCategoryResDTO> getFirstPageServeList(Long regionId) {
        // 1.校验参数
        if (regionId == null) {
            throw new CommonException("区域id不能为空");
        }
        Region region = regionMapper.selectById(regionId);
        if (region == null){
            throw new CommonException("区域不存在");
        }
        // 2.处理业务
        List<ServeCategoryResDTO> list = serverMapper.findServeIconCategoryByRegionId(regionId);
        //3.服务类型取前两个，每个类型下服务项取前4个
        //list的截止下标
        List<ServeCategoryResDTO> collect = list.stream().limit(2).collect(Collectors.toList());
        collect.forEach(v -> {
            //serveResDTOList的截止下标
            List<ServeSimpleResDTO> serveResDTOList = v.getServeResDTOList().stream().limit(4).collect(Collectors.toList());
            v.setServeResDTOList(serveResDTOList);
        });
        return collect;
    }
}
